package hng.service.store.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import hng.dto.store.*;
import hng.enums.FolderEnum;
import hng.enums.OrderStatusEnum;
import hng.interceptor.LoginInterceptor;
import hng.mapper.*;
import hng.model.*;
import hng.service.FileInfoService;
import hng.service.ProductImgService;
import hng.service.ProductSpecService;
import hng.service.store.StoreService;
import hng.vo.ProductCommentVO;
import hng.vo.store.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 店铺表 服务实现类
 * </p>
 *
 * @author 告白
 * @since 2024-06-27
 */
@Slf4j
@Service
public class StoreServiceImpl implements StoreService {

    @Autowired(required = false)
    private StoreMapper storeMapper;

    @Autowired(required = false)
    private ProductMapper productMapper;

    @Autowired(required = false)
    private ProductSpecMapper productSpecMapper;

    @Autowired(required = false)
    private ProductImgMapper productImgMapper;

    @Autowired(required = false)
    private ProductCommentMapper commentMapper;

    @Autowired(required = false)
    private OrdersMapper ordersMapper;

    @Autowired(required = false)
    private FileInfoService fileInfoService;

    @Autowired(required = false)
    private ProductImgService productImgService;

    @Autowired(required = false)
    private ProductSpecService productSpecService;

    /**
     * 分页查询商品列表
     */
    @Override
    public PageResult productList(ProductQuery productQuery) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Page<Object> objects = PageHelper.startPage(productQuery.getPageNum(), productQuery.getPageSize());
        List<ProductDO> productQueryList = productMapper.productByStore(loginUser.getStoreId());
        long size = objects.getTotal();
        PageResult pageResult = new PageResult(size, productQueryList);
        return pageResult;
    }

    /**
     * 删除单个商品
     */
    @Override
    public void productDelOne(Integer id) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        // 删除商品表
        int row1 = productMapper.delete(new LambdaQueryWrapper<ProductDO>()
                .eq(ProductDO::getId, id)
                .eq(ProductDO::getStoreId, loginUser.getStoreId())
        );

        if (row1 == 0) {
            return;
        }

        // 商品商品规格表
        int row2 = productSpecMapper.delete(new LambdaQueryWrapper<ProductSpecDO>()
                .eq(ProductSpecDO::getProductId, id)
        );

        // 商品图片表
        int row3 = productImgMapper.delete(new LambdaQueryWrapper<ProductImgDO>()
                .eq(ProductImgDO::getProductId, id)
        );
    }

    /**
     * 批量删除
     */
    @Transactional
    @Override
    public void productDelBatch(DelBatchDTO delBatchDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        // 批量删除商品
        productMapper.deleteBatchIdsAndShopId(delBatchDTO.getIdList(), loginUser.getStoreId());
        // TODO: 2024/7/5 下面2个有问题
        /**
         * org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'idList' not found. Available parameters are [arg0, collection, list]
         */
        // 批量删除商品的图片
        // productImgMapper.deleteByProductIds(delBatchDTO.getIdList());
        // 批量删除商品的规格
        // productSpecMapper.deleteByProductIds(delBatchDTO.getIdList());
    }

    /**
     * 获取商品列表
     * @return
     */
    @Override
    public List<ProductExcelVO> getProductList() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        List<ProductDO> productDOList = productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
                .eq(ProductDO::getStoreId, loginUser.getStoreId())
        );

        List<ProductExcelVO> productExcelVOList = productDOList.stream().map(obj -> {
            ProductExcelVO productExcelVO = new ProductExcelVO();
            BeanUtils.copyProperties(obj, productExcelVO);
            return productExcelVO;
        }).collect(Collectors.toList());
        return productExcelVOList;
    }

    /**
     * 分页查询评论列表
     */
    @Override
    public PageResult commentList(CommentQuery commentQuery) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Page<Object> objects = PageHelper.startPage(commentQuery.getPageNum(), commentQuery.getPageSize());
        List<ProductCommentVO> productQueryList = commentMapper.getListByStore(loginUser.getStoreId(), commentQuery.getKeyword());
        long size = objects.getTotal();
        PageResult pageResult = new PageResult(size, productQueryList);
        return pageResult;
    }

    /**
     * 分页查询订单列表
     */
    @Override
    public PageResult ordersList(OrdersQuery ordersQuery) {
        // 获取当前用户
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        // 设置页号和每页大小
        Page<Object> objects = PageHelper.startPage(ordersQuery.getPageNum(), ordersQuery.getPageSize());
        // 查询订单列表
        List<OrdersVO> ordersVOList = ordersMapper.getListByStore(loginUser.getStoreId(), ordersQuery.getOrderStatus());
        long size = objects.getTotal();
        PageResult pageResult = new PageResult(size, ordersVOList);
        return pageResult;
    }

    /**
     * 查询首页4个数据
     */
    @Override
    public TotalDataVO totalData() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        // 获取店铺商品总数量
        Integer productCount = productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getStoreId, loginUser.getStoreId()));
        // 评论总数量
        int commentCount = commentMapper.countCommentsByStoreId(loginUser.getStoreId());
        // 店铺总订单
        Integer orderCount = ordersMapper.selectCount(new LambdaQueryWrapper<OrdersDO>().eq(OrdersDO::getStoreId, loginUser.getStoreId()));
        // 交易数总价
        Double moneyCount = ordersMapper.moneyTotalByStore(loginUser.getStoreId());
        TotalDataVO totalDataVO = new TotalDataVO();
        totalDataVO.setProductTotal(productCount);
        totalDataVO.setCommentTotal(commentCount);
        totalDataVO.setOrderTotal(orderCount);
        totalDataVO.setMoneyTotal(moneyCount);

        return totalDataVO;
    }

    /**
     * 发货
     */
    @Override
    public void shipments(Integer orderId) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        OrdersDO ordersDO = new OrdersDO();
        ordersDO.setId(orderId);
        ordersDO.setStoreId(loginUser.getStoreId());
        ordersDO.setOrderStatus(OrderStatusEnum.PENDING_RECEIPT.getCode());
        ordersMapper.updateById(ordersDO);
    }

    /**
     * 添加商品
     * @param files
     */
    @Override
    public void addProduct(ProductDTO productDTO, MultipartFile[] files) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        // 当前店铺id
        Integer storeId = loginUser.getStoreId();
        // 上传图片 获取图片列表
        List<String> imgList = fileInfoService.uploadFiles(files, FolderEnum.PRODUCT_IMAGE.getDesc());
        ProductDO productDO = new ProductDO();
        BeanUtils.copyProperties(productDTO, productDO);
        productDO.setStoreId(storeId);
        // 设置封面图
        productDO.setCoverUrl(imgList.get(0));
        // 插入到商品表
        productMapper.insert(productDO);
        // 获取商品id
        Integer productId = productDO.getId();
        // 获取规格列表
        List<ProductSpecDO> specList = productDTO.getSpecList();
        for (ProductSpecDO obj : specList) {
            obj.setProductId(productDO.getId());
        }
        // 创建Img列表
        List<ProductImgDO> imgDOList = new ArrayList<>();
        for (String url : imgList) {
            ProductImgDO productImgDO = new ProductImgDO();
            productImgDO.setProductId(productId);
            productImgDO.setImgUrl(url);
            imgDOList.add(productImgDO);
        }

        // 插入到商品规格表
        productSpecService.saveBatch(specList);
        // 插入到商品图片表
        productImgService.saveBatch(imgDOList);

    }
}
